package com.adong.subclass;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author adong
 */
public class JoinedSubClassTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {
        Configuration configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    }

    @After
    public void destroy() {
        transaction.commit();
        session.close();
        sessionFactory.close();
    }
    /**
     * 优点:
     * 不需要要使用辨别者列
     * 子类独有的字段能添加非空约束
     *  没有冗余的字段
     */

    /**
     * 子类记录插入,要插入两张表
     */
    @Test
    public void SaveTest() {
        Person person = new Person();
        person.setAge(19);
        person.setName("adong");
        session.save(person);

        Student student = new Student();
        student.setAge(200);
        student.setName("波波");
        student.setSchool("清华大学");
        session.save(student);
    }

    /**
     * 查询
     * 1.查询父类的记录,做一个左外连接查询
     * 2.对于子类记录,做一个内连接的查询
     */
    @Test
    public void testQuery() {
        List persons = session.createQuery("FROM Person").list();
        System.out.println(persons.size());
        List student = session.createQuery("FROM Student").list();
        System.out.println(student.size());
    }
}
